<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Category;
use Validator;

class CategoryController  extends Controller
{
    public function index()
    {
    	$category=Category::get();
        $category = $this->GetTree($category->toArray(), 0, 0);

    	return view('admin.category.index',compact('category'));
    }

    public function create(Request $request)
    {
    	$category=Category::where('parent_id',0)->get();
        
    	return view('admin.category.create',compact('category'));
    }

    public function store(Request $request)
    {   
        $data=$request->intersect('name','tags','description','parent_id','icon');

        try {
            $this->Validator($data);
            Category::create($data);

        } catch (\Exception $e) {
            return parent::error($e->getMessage());
        }
    	
    	return parent::success('success',route('admin.category.index'));
    }


    public function edit(Request $request)
    {
    	$id=$request->id;
        $cat=Category::find($id);
        $category=Category::where('parent_id',0)->get();
    	return view('admin.category.edit',compact('category','cat'));
    }


    public function update(Request $request)
    {   
        $id=$request->id;
    	$data=$request->intersect('name','tags','description','parent_id','icon');
        Category::where('id',$id)->update($data);
    	return parent::success('success',route('admin.category.index'));
    }

    public function destroy(Request $request)
    {
    	$id=$request->id;
        Category::where('id',$id)->delete();
    	return parent::success('success',route('admin.category.index'));
    }

    public function Validator(array $data)
    {   
        $validator = Validator::make($data, [
            'name'      => 'required',
            'tags'      => 'required',
            'description'      => 'required|string', 
            
        ]);

        if ( $validator->fails()){
            $error = $validator->errors()->first();
            throw new \Exception($error,1);
        }
    } 

    private function GetTree($arr,$pid,$step){
        global $tree;
        foreach($arr as $key=>$val) {
            if($val['parent_id'] == $pid) {
                $flg = str_repeat('└―',$step);
                $val['name'] = $flg.$val['name'];
                $tree[] = $val;
                $this->GetTree($arr , $val['id'] ,$step+1);
            }
        }

        return $tree;
    }
}
